﻿using Eps.Ai.Common;
using InfonavaEye.common;
using InfonavaEye.components;
using InfonavaEye.enums;
using InfonavaEye.handler;
using InfonavaEye.Handler;
using InfonavaEye.model;
using InfonavaEye.model.wjapi;
using InfonavaEye.util;
using Sylan.Common.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace InfonavaEye.Forms
{
    public partial class BoxAreaForm : Form
    {
        FocusDistanceCurrentLimiter focusDistanceCurrentLimiter;


        //不抢焦点,非活动窗口
        protected override bool ShowWithoutActivation => true;

        /// <summary>
        /// 光源当前亮度
        /// </summary>
        public int CurrentLuminosity { get; set; }
        /// <summary>
        /// 镜头当前倍率
        /// </summary>
        public int CurrentAutoShotMagnification { get;  set;}
        /// <summary>
        /// 模式，1 添加，2修改,0 查看
        /// </summary>
        public int Mode { get; set; }

        /// <summary>
        /// 钉盒区域实体
        /// </summary>
        public BoxArea BoxArea { get; set; }

        /// <summary>
        /// 钉盒实体
        /// </summary>
        public BoxModel BoxModel { get; set; }

        /// <summary>
        /// 钉盒倾斜角度-x
        /// （左下角和右下角连成的线的角度）
        /// </summary>
        public double boxAngle = -9999;

        /// <summary>
        /// 钉盒倾斜角度-y
        /// （左上角和左下角连成的线的角度）
        /// </summary>
        public double boxAngleY = -9999;

        private bool timerStoped = false;
        System.Timers.Timer readLocationTimer;   // The auto exposure timer

        /// <summary>
        /// 默认坐标文本
        /// </summary>
        private string defaultXYZText = "0,0,0";

        /// <summary>
        /// 默认当前坐标
        /// </summary>
        private string defaultCurrentXYZText = "x,y,z";

        public event Action boxAreaCloseDelegate;

        private CameraHandler cameraHandler = CameraHandler.Instance;
        private PLCHandler plcHandler = PLCHandler.Instance;
        private LightHandler lightHandler = LightHandler.Instance;

        public BoxAreaForm()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false; //加载时 取消跨线程检查
        }

        private void BoxAreaForm_Load(object sender, EventArgs e)
        {
            this.lblTitle.PageTitle = this.Mode ==1 ?"添加区域":"编辑区域";
            this.btnLeftDownLocation.DisabledForeColor = Color.Gray;
            this.btnLeftUpLocation.DisabledForeColor = Color.Gray;
            this.btnRightDownLocation.DisabledForeColor = Color.Gray;
            this.btnLeftDownLocation.DisabledBackColor = Color.FromArgb(255, 200, 200, 200);
            this.btnLeftUpLocation.DisabledBackColor = Color.FromArgb(255, 200, 200, 200);
            this.btnRightDownLocation.DisabledBackColor = Color.FromArgb(255, 200, 200, 200);
            this.lblCurrentXYZ.Text = defaultCurrentXYZText;
            int drawingBoxWidth = drawingBox.Width;
            //drawingBox.Width = (int)(drawingBox.Height / 2048f * 3072f);
            drawingBox.Height = (int)(drawingBox.Width * 2048f / 3072f);
            //drawingBox.Location = new Point(drawingBox.Location.X + (drawingBoxWidth - drawingBox.Width) / 2, drawingBox.Location.Y);

            //图像参考线
            this.initPicCursor();
            this.initLuminosity();
            this.initCurrentAutoShotMagnification();
            //光源亮度
            this.setLuminosity();


            #region 坐标计算
            this.btnLeftUpLocation.Visible = this.Mode > 0;
            this.btnLeftDownLocation.Visible = this.Mode > 0;
            this.btnRightDownLocation.Visible = this.Mode > 0;
            this.txtAreaName.Enabled = this.Mode > 0;
            this.numRowCount.Enabled = this.Mode > 0;
            this.numColumnCount.Enabled = this.Mode > 0;
            this.txtColumnTitle.Enabled = this.Mode > 0;
            this.btnSure.Text = this.Mode == 2 ? "修改" : "添加";
            this.lblLeftUpLocation.Text = defaultXYZText;
            this.lblRightDownLocation.Text = defaultXYZText;
            this.lblCurrentXYZ.Text = defaultCurrentXYZText;
            this.initForm();
            #endregion

            ThreadHelper.ExcuteThreadTask(() =>
            {
                cameraHandler.captureImageDelegate -= CaptureImage;
                plcHandler.PLCInitCompleteDelegate += PLCHandler_PLCInitCompleteDelegate;
                focusDistanceCurrentLimiter = new FocusDistanceCurrentLimiter();
                plcHandler.StartPLC();
                cameraHandler.play(this.drawingBox);
                cameraHandler.captureImageDelegate += CaptureImage;
            }, 250);
        }

        private void PLCHandler_PLCInitCompleteDelegate()
        {
            InitAllTimers();

            this.Invoke(new Action(() =>
            {
                this.btnBack.Visible = true;
                this.btnSure.Visible = this.Mode > 0;
            }));
        }

        #region 图像参考线
        private void initPicCursor()
        {

            /*PictureBox xCrossLine = new PictureBox();
            PictureBox xCrossLine1 = new PictureBox();
            PictureBox xCrossLine2 = new PictureBox();
            PictureBox yCrossLine = new PictureBox();
            PictureBox yCrossLine1 = new PictureBox();
            PictureBox yCrossLine2 = new PictureBox();*/

            //圆型的最佳大小
            var marginTop = 40;
            var nailBestWidthOnView = drawingBox.Height - marginTop * 2;
            var nailBestHeightOnView = drawingBox.Height - marginTop * 2;
            var marginLeft = (drawingBox.Width - nailBestWidthOnView) / 2;

            xCrossLine.BackColor = System.Drawing.Color.Red;
            xCrossLine.TabStop = false;
            xCrossLine.Width = drawingBox.Width - 2 * marginLeft;
            xCrossLine.Height = 1;
            xCrossLine.Location = new Point(drawingBox.Location.X + marginLeft, drawingBox.Location.Y + marginTop);

            xCrossLine1.BackColor = System.Drawing.Color.Red;
            xCrossLine1.TabStop = false;
            xCrossLine1.Width = drawingBox.Width - 2 * marginLeft;
            xCrossLine1.Height = 1;
            xCrossLine1.Location = new Point(drawingBox.Location.X + marginLeft, drawingBox.Location.Y + drawingBox.Height / 2);

            xCrossLine2.BackColor = System.Drawing.Color.Red;
            xCrossLine2.TabStop = false;
            xCrossLine2.Width = drawingBox.Width - 2 * marginLeft;
            xCrossLine2.Height = 1;
            xCrossLine2.Location = new Point(drawingBox.Location.X + marginLeft, drawingBox.Location.Y + drawingBox.Height - marginTop);

            ////Y
            yCrossLine.BackColor = System.Drawing.Color.Red;
            yCrossLine.TabStop = false;
            yCrossLine.Width = 1;
            yCrossLine.Height = drawingBox.Height - 2 * marginTop;
            yCrossLine.Location = new Point(drawingBox.Location.X + (drawingBox.Width - nailBestWidthOnView) / 2, drawingBox.Location.Y + marginTop);

            yCrossLine1.BackColor = System.Drawing.Color.Red;
            yCrossLine1.TabStop = false;
            yCrossLine1.Width = 1;
            yCrossLine1.Height = drawingBox.Height - 2 * marginTop;
            yCrossLine1.Location = new Point(drawingBox.Location.X + drawingBox.Width / 2, drawingBox.Location.Y + marginTop);

            yCrossLine2.BackColor = System.Drawing.Color.Red;
            yCrossLine2.TabStop = false;
            yCrossLine2.Width = 1;
            yCrossLine2.Height = drawingBox.Height - 2 * marginTop;
            yCrossLine2.Location = new Point(drawingBox.Location.X + (drawingBox.Width + nailBestWidthOnView) / 2, drawingBox.Location.Y + marginTop);



            xPpperInnerBoxLine.BackColor = System.Drawing.Color.Red;
            xPpperInnerBoxLine.TabStop = false;
            xPpperInnerBoxLine.Width = drawingBox.Width - 2 * marginLeft - 100;
            xPpperInnerBoxLine.Height = 1;
            xPpperInnerBoxLine.Location = new Point(drawingBox.Location.X + 50 + marginLeft, drawingBox.Location.Y + marginTop + 50);

            xBelowInnerBoxLine.BackColor = System.Drawing.Color.Red;
            xBelowInnerBoxLine.TabStop = false;
            xBelowInnerBoxLine.Width = drawingBox.Width - 2 * marginLeft - 100;
            xBelowInnerBoxLine.Height = 1;
            xBelowInnerBoxLine.Location = new Point(drawingBox.Location.X + 50 + marginLeft, drawingBox.Location.Y + drawingBox.Height - marginTop - 50);


            yInnerBoxLeftLine.BackColor = System.Drawing.Color.Red;
            yInnerBoxLeftLine.TabStop = false;
            yInnerBoxLeftLine.Width = 1;
            yInnerBoxLeftLine.Height = drawingBox.Height - 2 * marginTop - 100;
            yInnerBoxLeftLine.Location = new Point(drawingBox.Location.X + 50 + (drawingBox.Width - nailBestWidthOnView) / 2, drawingBox.Location.Y + marginTop + 50);



            yInnerBoxrRghtLine.BackColor = System.Drawing.Color.Red;
            yInnerBoxrRghtLine.TabStop = false;
            yInnerBoxrRghtLine.Width = 1;
            yInnerBoxrRghtLine.Height = drawingBox.Height - 2 * marginTop - 100;
            yInnerBoxrRghtLine.Location = new Point(drawingBox.Location.X - 50 + (drawingBox.Width + nailBestWidthOnView) / 2, drawingBox.Location.Y + marginTop + 50);



            /*this.Controls.Add(xCrossLine);
            this.Controls.Add(xCrossLine1);
            this.Controls.Add(xCrossLine2);
            this.Controls.Add(yCrossLine);
            this.Controls.Add(yCrossLine1);
            this.Controls.Add(yCrossLine2);*/

            /* xCrossLine.Visible = false;
             yCrossLine.Visible = false;*/
        }
        #endregion

        private void BoxAreaForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            plcHandler.PLCInitCompleteDelegate -= PLCHandler_PLCInitCompleteDelegate;
            cameraHandler.captureImageDelegate -= CaptureImage;
            this.cameraHandler.pause();//暂停视频
            if (readLocationTimer != null)
            {
                timerStoped = true;
                readLocationTimer.Stop();
                readLocationTimer.Close();
            }
            if (boxAreaCloseDelegate != null)
            {
                boxAreaCloseDelegate.Invoke();
            }
        }
        private void initLuminosity() {
            if (this.Mode==2) {
                //修改模式下从模板区域中获取光源亮度
                CurrentLuminosity = this.BoxArea.lightLuminosity;
            }
            if (CurrentLuminosity == 0)
            {
                CurrentLuminosity = Config.LIGHT_SOURCE_LUMINOSITY_DEFAULT;
            }
            this.luminosityTrackBar.Value = CurrentLuminosity;
            this.adjustLuminosity();
        }

        private void initCurrentAutoShotMagnification()
        {
            if (this.Mode == 2)
            {
                //修改模式下从模板区域中获取光源亮度
                CurrentAutoShotMagnification = this.BoxArea.autoShotMagnification;
            }
            if (CurrentAutoShotMagnification == 0)
            {
                CurrentAutoShotMagnification = 7;
            }
            this.autoShotTrackBar.Value = CurrentAutoShotMagnification;
            this.autoShotValLbl.Text = CurrentAutoShotMagnification.ToString();
            AutoShotHelper.Instance.sendMsg(autoShotTrackBar.Value.ToString());
        }


        private void setLuminosity()
        {
           /* if (this.BoxModel == null) return;

            if (lightItems.Length >= 3)
            {
                this.radioLuminosity1.Checked = (this.BoxModel.LightLuminosity == lightItems[0]);
                this.radioLuminosity2.Checked = (this.BoxModel.LightLuminosity == lightItems[1]);
                this.radioLuminosity3.Checked = (this.BoxModel.LightLuminosity == lightItems[2]);
            }
            if (this.BoxModel.LightLuminosity == 0)
            {
                this.radioLuminosity1.Checked = true;
                this.BoxModel.LightLuminosity = lightItems[0];
            }
            lightHandler.ChangeLuminance(this.BoxModel.LightLuminosity);*/
        }

        bool closing = false;
        protected override void OnClosing(CancelEventArgs e)
        {
            if (cameraHandler.isCameraOpening)
            {
                e.Cancel = true; //取消关闭操作
                MessageBox.Show("相机正在连接中，无法中断，请稍后再尝试关闭", "提示", MessageBoxButtons.OK);
                return;
            }

            closing = true;
        }

        /// <summary>
        /// 初始化表单
        /// </summary>
        private void initForm()
        {
            if (this.Mode == 1)
            {
                this.BoxArea = new BoxArea() { code = Guid.NewGuid().ToString("N") };
                this.BoxArea.lightLuminosity = this.CurrentLuminosity;
                this.BoxArea.autoShotMagnification =this.CurrentAutoShotMagnification==0?7:this.CurrentAutoShotMagnification;
            }
            else
            {
                if (this.BoxArea == null)
                {
                    AutoCloseMessageBox.Show("未找到区域的数据");
                    return;
                }
                this.txtAreaName.Text = this.BoxArea.name;
                this.numColumnCount.Value = this.BoxArea.columnCount;
                this.numRowCount.Value = this.BoxArea.rowCount;
                this.txtColumnTitle.Text = String.Join(",", this.BoxArea.columnTitle);
                if (this.boxAngle != -9999)
                {
                    this.lblBoxAngle.Text = this.boxAngle.ToString();
                }
                this.twirlCheckBox.Checked = this.BoxArea.twirl180;
                this.parseAreaXYZ();
            }
        }

        /// <summary>
        /// 计算区域4个角的坐标
        /// </summary>
        private void parseAreaXYZ()
        {
            var rowCount = this.BoxArea.rowCount;
            var columnCount = this.BoxArea.columnCount;
            var startPoint = this.BoxArea.startPoint;
            var holdPitch = this.BoxArea.holdPitch;
            if (startPoint == null || rowCount == 0 || columnCount == 0 || holdPitch == null)
            {
                return;
            }

            var x = startPoint[0];
            var y = startPoint[1];
            var z = startPoint[2];
            var zIlluminant = startPoint[3];
            var xPitch = holdPitch[0];
            var yPitch = holdPitch[1];

            var rightDownPoint = new int[] { x, y, z ,zIlluminant };
            this.lblRightDownLocation.Text = String.Join(",", rightDownPoint);

            if (this.boxAngle != -9999)
            {
                //以右下角为基础点，计算左下角。
                var leftDownPoint = new int[] {
                    (int)(x + xPitch * (columnCount - 1) * Math.Cos(this.boxAngle * Math.PI / 180)),
                    (int)(y + xPitch * (columnCount - 1) * Math.Sin(this.boxAngle * Math.PI / 180)),
                    z,zIlluminant
                };
                this.lblLeftDownLocation.Text = String.Join(",", leftDownPoint);

                //以左下角为基础点，计算左上角
                var leftUpPoint = new int[] {
                    (int)(leftDownPoint[0] + yPitch * (rowCount - 1)* Math.Cos((90-this.boxAngle)* Math.PI / 180)),
                    (int)(leftDownPoint[1] + yPitch * (rowCount - 1)* Math.Sin((90-this.boxAngle) *Math.PI / 180)),
                    z,zIlluminant
                };
                this.lblLeftUpLocation.Text = String.Join(",", leftUpPoint);
            }
        }

        private void InitAllTimers()
        {
            readLocationTimer = new System.Timers.Timer(100);
            readLocationTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimerReadLocation);
            readLocationTimer.AutoReset = true;
            readLocationTimer.SynchronizingObject = this;
            readLocationTimer.Start();
        }

        private void OnTimerReadLocation(object sender, ElapsedEventArgs e)
        {
            readLocationTimer.Stop();
            this.readXYZ();
            if (!timerStoped)
            {
                readLocationTimer.Start();
            }
        }
        private int[] readXYZ()
        {
            try
            {
                Console.WriteLine("readXYZ BoxAreaForm");
                int[] xyz = plcHandler.readCurrentXYZ();// new int[] { 200, 300, 500 };// 
                lblCurrentXYZ.Text = String.Format("{0},{1},{2},{3}", xyz[0], xyz[1], xyz[2], xyz[3]);
                Console.WriteLine("读取到当前坐标：{0}", lblCurrentXYZ.Text);
                return xyz;
            }
            catch (Exception ex)
            {
                AutoCloseMessageBox.Show(ex.Message);
                return null;
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
            this.Close();
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.txtAreaName.Text))
            {
                AutoCloseMessageBox.Show("请输入区域名称");
                return;
            }
            if (this.numRowCount.Value == 0)
            {
                AutoCloseMessageBox.Show("请输入区域行数");
                return;
            }
            if (this.numColumnCount.Value == 0)
            {
                AutoCloseMessageBox.Show("请输入区域列数");
                return;
            }
            if (String.IsNullOrEmpty(this.txtColumnTitle.Text))
            {
                AutoCloseMessageBox.Show("请输入列标识");
                return;
            }
            if (defaultXYZText.Equals(this.lblLeftUpLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域左上上位置的坐标");
                return;
            }
            if (defaultXYZText.Equals(this.lblRightDownLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域右下位置的坐标");
                return;
            }
            if (defaultXYZText.Equals(this.lblLeftDownLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域左下位置的坐标");
                return;
            }
            if (this.boxAngle == -9999)
            {
                AutoCloseMessageBox.Show("请先填入区域3个位置的坐标，自动计算出钉盒倾斜角度");
                return;
            }

            this.BoxArea.name = this.txtAreaName.Text;
            this.BoxArea.rowCount = (int)this.numRowCount.Value;
            this.BoxArea.columnCount = (int)this.numColumnCount.Value;
            this.BoxArea.columnTitle = this.txtColumnTitle.Text.Split(new char[] { ',', '，', ' ' });
            //测试数据
            /* this.lblRightDownLocation.Text = "1056,-1580,6901";
             this.lblLeftDownLocation.Text = "17182,-1510,6901";
             this.lblLeftUpLocation.Text = "17182,198,6901";*/
            this.calcBoxAngle();
            if (this.calcAreaXYZ())
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private bool calcAreaXYZ()
        {
            var rightDownPoint = this.lblRightDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            var leftUpPoint = this.lblLeftUpLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            var leftDownPoint = this.lblLeftDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (rightDownPoint.Length < 3 || leftUpPoint.Length < 3 || leftDownPoint.Length < 3)
            {
                AutoCloseMessageBox.Show("区域位置坐标数据不正常");
                return false;
            }
            var xPitch = 0;
            if (this.BoxArea.columnCount > 1)
            {
                xPitch = (int)MathUtil.calcDistance((double)rightDownPoint[0], (double)rightDownPoint[1],
                    (double)leftDownPoint[0], (double)leftDownPoint[1]) / (this.BoxArea.columnCount - 1);
            }

            var yPitch = 0;
            if (this.BoxArea.rowCount > 1)
            {
                yPitch = (int)MathUtil.calcDistance((double)leftUpPoint[0], (double)leftUpPoint[1],
                    (double)leftDownPoint[0], (double)leftDownPoint[1]) / (this.BoxArea.rowCount - 1);
            }

            if (xPitch < 0 || yPitch < 0)
            {
                AutoCloseMessageBox.Show("区域坐标计算出的孔距不正常");
                return false;
            }
            this.BoxArea.holdPitch = new int[] { xPitch, yPitch };
            this.BoxArea.startPoint = rightDownPoint;
            return true;
        }

        private void drawingBox_Paint(object sender, PaintEventArgs e)
        {
            PictureBox p = (PictureBox)sender;
            Pen pp = new Pen(Color.FromArgb(255, 0, 77, 203));
            e.Graphics.DrawRectangle(pp, e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.X + e.ClipRectangle.Width - 1, e.ClipRectangle.Y + e.ClipRectangle.Height - 1);
        }

        private void btnLeftUpLocation_Click(object sender, EventArgs e)
        {
            if (checkCurrentXYZ())
            {
                this.lblLeftUpLocation.Text = this.lblCurrentXYZ.Text;
            }
        }

        private void btnRIghtDownLocation_Click(object sender, EventArgs e)
        {
            if (checkCurrentXYZ())
            {
                this.lblRightDownLocation.Text = this.lblCurrentXYZ.Text;
                this.calcBoxAngle();
            }
        }

        private void btnLeftDownLocation_Click(object sender, EventArgs e)
        {
            if (checkCurrentXYZ())
            {
                this.lblLeftDownLocation.Text = this.lblCurrentXYZ.Text;
                this.calcBoxAngle();
            }
        }

        private void calcBoxAngle()
        {
            if (defaultXYZText.Equals(this.lblLeftDownLocation.Text))
            {
                return;
            }
            if (defaultXYZText.Equals(this.lblRightDownLocation.Text))
            {
                return;
            }

            var rightDownPoint = this.lblRightDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            //var leftUpPoint = this.lblLeftUpLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            var leftDownPoint = this.lblLeftDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (rightDownPoint.Length < 3 || leftDownPoint.Length < 3)
            {
                return;
            }

            this.boxAngle = MathUtil.anglevalue(rightDownPoint[0], rightDownPoint[1], leftDownPoint[0], leftDownPoint[1]);//校准前的对角线的角度
            this.boxAngle = Math.Round(this.boxAngle, 8, MidpointRounding.AwayFromZero);//保留8位小数
            this.lblBoxAngle.Text = this.boxAngle.ToString();

            //this.boxAngleY = MathUtil.anglevalue(leftDownPoint[0], leftDownPoint[1], leftUpPoint[0], leftUpPoint[1]);//校准前的对角线的角度
            //this.boxAngleY = Math.Round(this.boxAngleY, 8, MidpointRounding.AwayFromZero);//保留8位小数
            //this.lblBoxAngle.Text = this.boxAngle.ToString();
        }

        private bool checkCurrentXYZ()
        {
            if (defaultCurrentXYZText.Equals(this.lblCurrentXYZ.Text))
            {
                AutoCloseMessageBox.Show("当前坐标没有数据");
                return false;
            }
            return true;
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btnLeftUpLocate_Click(object sender, EventArgs e)
        {
            if (defaultXYZText.Equals(this.lblLeftUpLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域左上位置的坐标");
                return;
            }
            var leftUpPoint = this.lblLeftUpLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (leftUpPoint.Length < 3)
            {
                AutoCloseMessageBox.Show("区域左上位置坐标数据不正常");
                return;
            }
            toggleButtonStatus(1);
            this.moveToPoint(leftUpPoint);
        }

        private void btnLeftDownLocate_Click(object sender, EventArgs e)
        {
            if (defaultXYZText.Equals(this.lblLeftDownLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域左下位置的坐标");
                return;
            }
            var leftDownPoint = this.lblLeftDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (leftDownPoint.Length < 3)
            {
                AutoCloseMessageBox.Show("区域左下位置坐标数据不正常");
                return;
            }
            toggleButtonStatus(2);
            this.moveToPoint(leftDownPoint);
        }

        private void btnRightDownLocate_Click(object sender, EventArgs e)
        {
           /* plcHandler.getLimitLocation();
            return;*/
            if (defaultXYZText.Equals(this.lblRightDownLocation.Text))
            {
                AutoCloseMessageBox.Show("请填入区域右下位置的坐标");
                return;
            }
            var rightDownPoint = this.lblRightDownLocation.Text.Split(new char[] { ',' }).Select(p => int.Parse(p)).ToArray();
            if (rightDownPoint.Length < 3)
            {
                AutoCloseMessageBox.Show("区域右下位置坐标数据不正常");
                return;
            }
            toggleButtonStatus(3);
            this.moveToPoint(rightDownPoint);
        }

        bool moving = false;
        private void moveToPoint(int[] point)
        {
            if (point == null || point.Length == 0)
            {
                AutoCloseMessageBox.Show("坐标不正确");
                return;
            }

            if (moving) return;

            ThreadHelper.ExcuteThreadTask(() =>
            {
                timerStoped = true;
                readLocationTimer.Stop();
                btnSure.Enabled = false;
                btnSure.Text = "移动中";
                try
                {
                    plcHandler.moveToXYZandCapture(point[0], point[1], point[2], point[3], false);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    moving = false;
                    timerStoped = false;
                    readLocationTimer.Start();
                    btnSure.Enabled = true;
                    this.btnSure.Text = this.Mode == 2 ? "修改" : "添加";
                    toggleButtonStatus(0);
                }
            });
        }

        /// <summary>
        /// 切换按钮状态(参数 what : 1 左上，2.左下，3.右下,0.没有按下按钮)
        /// </summary>
        /// <param name="what"> 1 左上，2.左下，3.右下,0.没有按下按钮</param>
        private void toggleButtonStatus(int what)
        {
            this.btnLeftUpLocate.Enabled = what == 0;
            this.btnLeftUpLocate.Text = what == 1 ? "移动中" : "移动到这个点";

            this.btnLeftDownLocate.Enabled = what == 0;
            this.btnLeftDownLocate.Text = what == 2 ? "移动中" : "移动到这个点";

            this.btnRightDownLocate.Enabled = what == 0;
            this.btnRightDownLocate.Text = what == 3 ? "移动中" : "移动到这个点";

            this.btnRightDownLocation.Enabled = what == 0;
            this.btnLeftDownLocation.Enabled = what == 0;
            this.btnLeftUpLocation.Enabled = what == 0;
        }

        private void btnRefreshPic_Click(object sender, EventArgs e)
        {
            ThreadHelper.ExcuteThreadTask(() =>
            {
                this.cameraHandler.play(this.drawingBox);
            });
        }

        private void panel3_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        /// <summary>
        /// 获取光源亮度（1,2,3 三档）
        /// </summary>
        /// <returns></returns>
        private int getLuminosity()
        {
           /* if (lightItems.Length >= 3)
            {
                if (this.radioLuminosity1.Checked)
                {
                    return lightItems[0];
                }
                else if (this.radioLuminosity2.Checked)
                {
                    return lightItems[1];
                }
                else
                {
                    return lightItems[2];
                }
            }*/
            return Config.LIGHT_SOURCE_LUMINOSITY_DEFAULT;
        }

        //改变光源亮度
        private void radioLuminosity1_CheckedChanged(object sender, EventArgs e)
        {
            int luminosity = getLuminosity();
            this.BoxModel.LightLuminosity = luminosity;
            lightHandler.ChangeLuminance(luminosity);
        }

        /// <summary>
        /// 打开光源亮度调节
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLightAdjust_Click(object sender, EventArgs e)
        {
            if (this.BoxModel == null) {
                this.BoxModel = new BoxModel();
            }
            if (this.BoxModel.LightLuminosity == 0)
            {
                this.BoxModel.LightLuminosity = Config.LIGHT_SOURCE_LUMINOSITY_DEFAULT;
            }
            LuminositySettingForm form = new LuminositySettingForm();
            form.CurrentLuminosity = this.BoxModel.LightLuminosity;
            if (form.ShowDialog() == DialogResult.OK)
            {
                this.BoxModel.LightLuminosity = form.CurrentLuminosity;
            }
        }

        //增加光源设置
        private void btnMinus_Click(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {

                if (luminosityTrackBar.Value > 10)
                {
                    int chageAfterVal = luminosityTrackBar.Value - 10;
                    if (chageAfterVal <= luminosityTrackBar.Minimum)
                    {
                        luminosityTrackBar.Value = luminosityTrackBar.Minimum;
                    }
                    else
                    {
                        luminosityTrackBar.Value -= 10;
                    }
                    // luminosityTrackBar.Value -= 10;
                    this.adjustLuminosity();
                }
            }));
        }

        private void btnPlus_Click(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                if (luminosityTrackBar.Value < luminosityTrackBar.Maximum) {
                    int chageAfterVal = luminosityTrackBar.Value + 10;
                    if (chageAfterVal >= luminosityTrackBar.Maximum)
                    {
                        luminosityTrackBar.Value = luminosityTrackBar.Maximum;
                    }
                    else
                    {
                        luminosityTrackBar.Value += 10;
                    }
                    this.adjustLuminosity();
                }

            }));
        }

        /// <summary>
        /// 调整光源亮度
        /// </summary>
        private void adjustLuminosity()
        {
            lblLuminosity.Text = luminosityTrackBar.Value.ToString();
            this.CurrentLuminosity = luminosityTrackBar.Value;
            if (this.BoxArea!=null) {
                this.BoxArea.lightLuminosity = this.CurrentLuminosity;
            }

            lightHandler.ChangeLuminance(luminosityTrackBar.Value);
        }

        private void luminosityTrackBar_Scroll(object sender, EventArgs e)
        {
            lblLuminosity.Text = luminosityTrackBar.Value.ToString();
        }

        private void luminosityTrackBar_MouseUp(object sender, MouseEventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                this.adjustLuminosity();
            }));
        }

        private void changeColumnTitle(object sender, EventArgs e) {
            int startColumn = int.Parse(this.columnTitleStartTextBox.Text);
            int endCount= int.Parse(this.columnTitleEndTextBox.Text);
            int stepping = int.Parse(this.steppingTextBox.Text);
            string oldVal = this.txtColumnTitle.Text;
            int newColumnName = startColumn;
            for (int i = 0; i < endCount; i++)
            {
                if (i != 0) {
                    newColumnName = newColumnName + stepping;
                } 
                if (string.IsNullOrEmpty(oldVal))
                {
                    oldVal = newColumnName.ToString();
                }
                else {
                    string lastStr= oldVal.Substring(oldVal.Length-1,1);
                    if (",".Equals(lastStr)) {
                        oldVal = oldVal.Substring(0, oldVal.Length - 1);
                    }
                    oldVal = oldVal + "," + newColumnName.ToString();
                }
            }
            this.txtColumnTitle.Text = oldVal;
        }
  
        
        private void autoShotBtnMinus_Click(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {

                if (autoShotTrackBar.Value > 7)
                {
                    int chageAfterVal = autoShotTrackBar.Value - 1;
                    if (chageAfterVal <= autoShotTrackBar.Minimum)
                    {
                        autoShotTrackBar.Value = autoShotTrackBar.Minimum;
                    }
                    else
                    {
                        autoShotTrackBar.Value -= 1;
                    }
                    this.autoShotValLbl.Text = autoShotTrackBar.Value.ToString();
                    this.saveAutoShotMagnification();
                    AutoShotHelper.Instance.sendMsg(autoShotTrackBar.Value.ToString());
                }
            }));
        }

        private void autoShotBtnPlus_Click(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {

                if (autoShotTrackBar.Value < autoShotTrackBar.Maximum)
                {
                    int chageAfterVal = autoShotTrackBar.Value +1;
                    if (chageAfterVal >= autoShotTrackBar.Maximum)
                    {
                        autoShotTrackBar.Value = autoShotTrackBar.Maximum;
                    }
                    else
                    {
                        autoShotTrackBar.Value++;
                    }
                    this.autoShotValLbl.Text=autoShotTrackBar.Value.ToString();
                    this.saveAutoShotMagnification();
                    AutoShotHelper.Instance.sendMsg(autoShotTrackBar.Value.ToString());
                }
            }));
        }
        

        private void autoShotTrackBar_Scroll(object sender, EventArgs e)
        {
            this.autoShotValLbl.Text = autoShotTrackBar.Value.ToString();
        }

        private void autoShotTrackBar_MouseUp(object sender, MouseEventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                this.saveAutoShotMagnification();
                AutoShotHelper.Instance.sendMsg(autoShotTrackBar.Value.ToString());
            }));
        }

        private void saveAutoShotMagnification()
        {
            this.CurrentAutoShotMagnification = autoShotTrackBar.Value;
            if (this.BoxArea != null)
            {
                this.BoxArea.autoShotMagnification = this.CurrentAutoShotMagnification;
            }

        }
        /// <summary>
        /// 调用相机的抓拍
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void captureBtn_Click(object sender, EventArgs e) {
            cameraHandler.createImageDir();
            cameraHandler.StartCapture();

        }

        private string currentPreImgPath;
        private string currentPreStraightImggPath;
        private void CaptureImage(string imgPath) {
            this.currentPreImgPath = imgPath;
            string straightImg=   StraightHelper.straight(imgPath,0);
            if (straightImg.EndsWith(".jpg"))
            {
                this.currentPreStraightImggPath = straightImg;
                this.Invoke(new Action(() =>
                {
                    this.straightenImgPictureBox.Load(straightImg);
                }));
            }
          
        }



        private void twirlCheckBoxCheckedChanged(object  sender,EventArgs  args) {
            if (this.currentPreStraightImggPath == null ||"".Equals(this.currentPreStraightImggPath)) {
                    return;
            }
            string newFilePath = this.currentPreStraightImggPath;
            if (this.twirlCheckBox.Checked)
            {
                //图片翻转180度
                newFilePath = this.currentPreStraightImggPath.Replace(".jpg", "_180.jpg");
                ImageUtils.RotateAndSaveImage(this.currentPreStraightImggPath, newFilePath);
                if (this.BoxArea != null)
                {
                    this.BoxArea.twirl180 =true;
                }
            }
            this.Invoke(new Action(() =>
            {
                Thread.Sleep(100);
                this.straightenImgPictureBox.Load(newFilePath);
            }));
        }

    }

}
